#!/usr/bin/env python
# $Id: hg.py df54dec975f4 2012/09/09 20:22:40 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__  = "$Revision: df54dec975f4 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-09-09 20:22:40Z $"

import optparse
import os
import sys

from venya.lib import cmdparser, stdlib, scm

class scmutil(cmdparser.GetOpt):
   option_list = (
         optparse.make_option("-u", "--url", type = "str",
            help = "Mercurial URL", dest = "url"),
         optparse.make_option("-U", "--user", type = "str",
            help = "Username to use for mercurial repository", dest = "user"),
         optparse.make_option("-d", "--directory", type = "str",
            help = "Directory to checkout the repository", dest = "directory"),
         optparse.make_option("-m", "--message", type = "str",
            help = "Checkin message from the commandline", dest = "message"),
   ) + cmdparser.GetOpt.option_list

   usage = "commands [ options ] [ files ]"

   help = """
   Program to use hg/mercurial command directly using a python script instead of
   executing a subprocess commands!

   To checkout a repository
   hg.py checkout -u <URL> -d <DIRECTORY>
   Note: keyword co can also be used instead of checkout if needed!"

   To commit a file to the repository, this commit to the local repository and
   pushes the changes to the remote as well
   hg.py commit -u URL files
   Note: Keyword ci can also be used instead of commit if needed!

   To print help
   hg.py help would print help WRT to commands,
   hg.py --help would print help for the options

   """

   def __init__(self, **kwargs):
      super(scmutil, self).__init__(**kwargs)
      self._hg = None

   def scmhelp(self):
      self.printhelp()
      print
      print("%s commands" %str(self))
      print("\tcommit | ci   [ Checkin/commit the change to repository ]")
      print("\tcheckout | co [ Checkout from the repository ]")
      print("\tupdate | up   [ Sync changes from repository ]")
      print("\tadd | include [ Add files/directory to the repository ]")
      print("\thelp | ?      [ prints this help ]")

   @cmdparser.getopts
   def handle(self):
      command = None
      try:
         command = self.arguments[1]
      except IndexError:
         self.error("Need command to proceed!")

      files = []
      try:
         files = self.arguments[2:]
      except IndexError:
         pass

      if command in ('help', '?'):
         self.scmhelp()
      else:
         self._hg = scm.mercury(self.options.url)
         self._hg.addDir(self.options.directory)

         if command in ('commit', 'ci'):
            self._hg.commit(self.options.message, files)
         elif command in ('checkout', 'co'):
            self._hg.checkout()
         elif command in ('update', 'up'):
            self._hg.update()
         elif command in ('add', 'include'):
            self._hg.add(files)
         elif command in ('sum', 'summary'):
            self._hg.summary()
         else:
            self.scmhelp()

if __name__ == "__main__":
   scm = None
   try:
      scm = scmutil(version = 1.0, args = sys.argv)
      if len(scm) <= 1:
         scm.printhelp()
      else:
         scm.handle()
   except cmdparser.GetOptError as err:
      print(err)
      sys.exit(1)

